package com.example.framework;

import org.netbeans.jemmy.operators.*;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class FolderHelper extends BaseHelper {

    public FolderHelper(HelperManager manager) {
        super(manager);
    }

    public Folders getFolders() {
        List<String> folderList = new ArrayList<String>();
        JTreeOperator folderTree = new JTreeOperator(mainFrame);
        Object[] folders = folderTree.getChildren(folderTree.getRoot());
        for (Object folder : folders){
            folderList.add("" + folder);
        }
        return new Folders(folderList);
    }

    public String createFolder(String folderName) {
        manager.getMenuHelper().createFolder();
        JDialogOperator dialog = new JDialogOperator(mainFrame);
        new JTextFieldOperator(dialog).setText(folderName);
        new JButtonOperator(dialog, "OK").push();
        return waitMessageDialog("Warning", 3000);
    }

    private String waitMessageDialog(String title, int timeout) {
        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        while (currentTime < startTime + timeout){
            JDialog dialog = JDialogOperator.findJDialog(mainFrame.getOwner(), title, false, false);
            if (dialog != null){
                JDialogOperator dialogOperator = new JDialogOperator(dialog);
                String message = new JLabelOperator(dialogOperator).getText();
                dialogOperator.requestClose();
                return message;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentTime = System.currentTimeMillis();
        }
        return null;
    }

    public void removeFolderByIndex(int index) {
        JTreeOperator folderTree = new JTreeOperator(mainFrame);
        folderTree.selectRow(index);
        manager.getMenuHelper().deleteFolder();
        JDialogOperator dialog = new JDialogOperator(mainFrame);
        new JButtonOperator(dialog, "Yes").push();
    }
}
